package com.hello.pet.service.system.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hello.pet.common.constant.WxConstant;
import com.hello.pet.common.exception.BaseException;
import com.hello.pet.service.system.dto.WxAuthDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WxUtil {

    @Value("${app.appID}")
    private String appId;

    @Value("${app.appSecret}")
    private String appSecret;

    public WxAuthDto getWxKeyAndOpenId(String code){
        String url = String.format(WxConstant.CODE2_SESSION,appId,appSecret,code);
        try {
            String response = HttpUtil.get(url);
            JSONObject responseJson = JSONUtil.parseObj(response);
            //失败
            if (!responseJson.get("errcode").equals("0")){
                throw new BaseException("请求微信服务错误!message:{"+responseJson.get("errmsg")+"}");
            }
            //成功,处理数据
            return new WxAuthDto(responseJson.get("openid").toString(),responseJson.get("session_key").toString(),responseJson.get("unionid").toString());
        }catch (Exception ex){
            throw new BaseException("登录失败!",ex);
        }
    }
}
